#!/bin/bash

# Execution starts here

# Check if running inside a terminal

if [ -t 1 ]; then
	is_tty=true
else
	is_tty=false
fi

# Try sourcing configuration file

source $HOME/.config/fileopener.config 2>/dev/null || source /etc/fileopener.config 2>/dev/null

# Check if the configuration file has been loaded

if ! declare -p mime_types >/dev/null; then
	if $is_tty; then
		echo "Configuration file invalid or missing" 1>&2
	else
		notify-send "Fileopener" "Configuration file invalid or missing"
	fi
	exit 1
fi

# Throw error if no argument

if [ -z "$1" ]; then
	if $is_tty; then
		echo "Invalid usage: no file specified" 1>&2
	else
		notify-send "Fileopener" "Invalid usage: no file specified"
	fi
	exit 1
fi

# Removing "file://" from the start of the name, if present, to not have to deal with it later

de_filed_1="${1#file://}"

# Get the mime type of the argument
type=$(file --mime-type "$de_filed_1" 2>/dev/null)
type="${type##* }"
type="${type%%/*}"


# If the mime type is empty 

if [ -z "$type" ]; then
	# if it's not a type, try with a url
		# Try to see if any known URL matches, if it does, open the relative program and terminate the opener
	for i in "${!url_types[@]}"; do
		if echo $de_filed_1 | grep -Eq "^${url_types[$i]}"; then
			if $is_tty; then
				${url_openers_terminal[$i]} "$de_filed_1"
			else
				${url_openers[$i]} "$de_filed_1"
			fi
			exit 0
		fi
	done
	# If it's not a URL either, the argument is invalid -> throw an error
	if $is_tty; then
		echo "Error: $1 is not a file/directory/known URL" 1>&2;
	else
		notify-send "Fileopener" "\"$1\" is not a file or knwon URL"
	fi
	exit 1
fi


# Do the same as URLs, but for extensions

for i in ${!extensions[@]}; do
	if [ "${de_filed_1##*.}" == "${extensions[$i]}" ]; then
		if $is_tty; then
			${extension_openers[$i]} "$de_filed_1"
		else
			${extension_openers_terminal[$i]} "$de_filed_1"
		fi
		exit 0
	fi
done


# if the chosen file is an application, run it
if [ "$type" == "application" ]; then
	# If the file name doesn't start with either "/" or "./", prepend "./" to it before running
	if echo $de_filed_1 | grep -Eq '^(/|\./)'; then
		"$de_filed_1"
	else
		./"$de_filed_1"
	fi
	exit 0
fi



# Do the same as URLs, but for mime types

for i in ${!mime_types[@]}; do
	if [ "$type" == "${mime_types[$i]}" ]; then
		if $is_tty; then
			${mime_openers_terminal[$i]} "$de_filed_1"
		else
			${mime_openers[$i]} "$de_filed_1"
		fi
		exit 0
	fi
done

if $is_tty; then
	echo "Unknown mime type: $type" 1>&2
else
	notify-send "Fileopener" "Unknown type \"$type\""
fi

exit 1
